import http.client, urllib.request, urllib.parse, urllib.error, base64
import json
import pymysql

#获取领域
def insertField(db,Id,FN):
    result = []
    result.append((Id, FN))
    inesrt_re = "insert into field(id,FN) values (%s,%s)"
    cursor = db.cursor()
    cursor.executemany(inesrt_re, result)
    db.commit()

def insertRelate(db,FC,Id):
    for item in FC:
        insertField(db, item["FId"], item["FN"])
        result = []
        result.append((Id,item["FId"]))
        inesrt_re = "insert into relate(pId,cId) values (%s,%s)"
        cursor = db.cursor()
        cursor.executemany(inesrt_re, result)
        db.commit()


def reviewdata_insert(db):
    try:
        f = open("D://fields.txt","r")
        i=0
        for line in f:
            i+=1
            print(u'正在提取第%s条记录' % i)
            Id=""
            FN=""
            FC=""
            if "Id" in eval(line).keys():
                Id=eval(line)["Id"]
            if "FN" in eval(line).keys():
                FN=eval(line)["FN"]
            insertField(db, Id, FN)
            if "FC" in eval(line).keys():
                FC=eval(line)["FC"]
                if FC != "":
                    insertRelate(db,FC,Id)
        f.close()
        print("over")
    except Exception as e:
        print("[Errno {0}] {1}".format(e.errno, e.strerror))



if __name__ == "__main__":  # 起到一个初始化或者调用函数的作用
    # db = pymysql.connect("localhost:3398", "root", "123456", "dataService", charset='utf8')
    db = pymysql.Connect(
        host='127.0.0.1',
        port=3306,
        user='root',
        passwd='123456',
        db='dataservice',
        charset='utf8'
    )
    cursor = db.cursor()
    # prem(db)
    reviewdata_insert(db)
    cursor.close()




